package modelnew;

import java.awt.Point;

/**
 * This class represents a part of the board. Since the 
 * parts on the board a polygon, the part is represented
 * as an array of points in the polygon.
 * @author Netanel
 *
 */
public class Part {
	
	// Data Members
	private Point[] m_polygonPoints;
	private boolean m_isTaken = false;
	
	// Constructor
	Part(Point[] polygonPoints) {
		m_polygonPoints = polygonPoints; 
	}
	
	// Access Methods
	public Point[] getPoints() {
		return m_polygonPoints;
	}
	
	/**
	 * Check whether this part is taken
	 * @return is taken.
	 */
	public boolean isTaken() {
		return m_isTaken;
	}
	
	/**
	 * Mark this part as taken
	 */
	public void markTaken() {
		m_isTaken = true;
	}
	
	/**
	 * Returns whether this part contains the given point.
	 * @param point The point to check
	 * @return True if the point is in the part, else otherwise.
	 */
	public boolean containsPoint(Point point) {
		int polySides = m_polygonPoints.length;
		
		int j = polySides - 1;
		double y = point.getY();
		double x = point.getX();
		boolean oddNodes = false;
		
		for (int i = 0; i < polySides; i++) {
			if (((m_polygonPoints[i].getY() < y && m_polygonPoints[j].getY() >= y)) ||
				(m_polygonPoints[j].getY() < y && m_polygonPoints[i].getY() >= y)) {
				if (m_polygonPoints[i].getX()  + (y - m_polygonPoints[i].getY()) / 
				   (m_polygonPoints[j].getY() - m_polygonPoints[i].getY()) * 
				   (m_polygonPoints[j].getX() - m_polygonPoints[i].getX()) <= x) {
					oddNodes = !oddNodes;
				}
				j=i;
			}
		}
		
		return oddNodes;
	}
}